/**
 * 
 */
package com.xxl.job.config;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.GsonTool;

/**
 * 描述：
 * 
 * <pre>
 * token 拦截处理
 * </pre>
 * 
 * @author qizai
 * @version: 0.0.1 2021年5月10日-下午4:00:52
 *
 */
public class XxlJobTokenHandlerInterceptor implements HandlerInterceptor {
	private final static Logger log = LoggerFactory.getLogger(XxlJobTokenHandlerInterceptor.class);
	public static final String		XXL_JOB_ACCESS_TOKEN	= "XXL-JOB-ACCESS-TOKEN";
	public static final String		TOKEN_FAIL				= GsonTool
			.toJson(new ReturnT<>(ReturnT.FAIL_CODE, "token无效."));
	private XxlJobAdminProperties	xxlJobAdminProperties;

	/*
	 * Controller方法调用前，返回true表示继续处理
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = request.getHeader(XXL_JOB_ACCESS_TOKEN);
		if (null == xxlJobAdminProperties) {
			xxlJobAdminProperties = XxlJobAutoConfiguration.getApplicationContext()
					.getBean(XxlJobAdminProperties.class);
		}
		if (!Optional.ofNullable(token).filter(x -> x.equals(xxlJobAdminProperties.getAccessToken())).isPresent()) {
			writerJson(response, TOKEN_FAIL);
			return false;
		}
		return true;
	}

	public static void writerJson(HttpServletResponse response, String text) {
		try {
			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
			response.getOutputStream().write(text.getBytes());
		} catch (IOException e) {
			log.error("HttpServletResponse writerText Exception.", e);
		}
	}
}
